package com.bjpowernode.core;

import com.bjpowernode.constant.Constant;

import java.util.concurrent.atomic.LongAdder;

/**
 * 展示下载信息的线程
 */
public class DownloadInfoThread implements Runnable{

    //文件大小
    private long httpFileContentLength;

    //本地文件已下载的大小
   // public double finishedSize;

    //前一次下载的大小
    public double preDownSize;

    //本次累计下载的大小（其他线程读取）
    public static volatile LongAdder downSize = new LongAdder();

    public DownloadInfoThread(long httpFileContentLength) {
        this.httpFileContentLength = httpFileContentLength;
    }

    @Override
    public void run() {
        //计算文件总大小,保存两位小数
        String httpFileSie = String.format("%.2f", httpFileContentLength / Constant.MB);

        //计算下载速度，单位：kb
        int speed = (int) (downSize.doubleValue() - preDownSize) / 1024;
        preDownSize = downSize.doubleValue();

        //计算剩余文件大小
        double remainSize = httpFileContentLength - downSize.doubleValue();

        //计算剩余时间
        String remainTime = String.format("%.1f", remainSize / 1024d / speed);

        //如果remainTime是无限大
        if ("Infinity".equalsIgnoreCase(remainTime)) {
            remainTime = "-";
        }

        //已下载大小
        String currentFileSize = String.format("%.2f", downSize.doubleValue() / Constant.MB);

        //输出下载信息
        String speedInfo = String.format("已下载：%sMB/%sMB，速度：%skb/s，剩余时间：%s秒", currentFileSize, httpFileSie, speed, remainTime);

        //在原有输出信息替换字符串后
        System.out.print("\r");
        System.out.print(speedInfo);

    }
    }

